<template>
  <div class="duty">
    <div class="screen_box">
      <div class="select_box">
        <el-input
          placeholder="请输入姓名搜索"
          v-model="name"
          class="input-with-select"
          size="mini"
          clearable
          @keyup.enter.native="selectFun">
          <el-button slot="append" size="mini" @click="selectFun">查询</el-button>
        </el-input>
      </div>
      <div class="btn">
        <el-button class="btnBg" type="primary" size="small" @click="importBankCard">导入</el-button>
        <el-button class="btnBg" type="primary" size="small" @click="addBankCard">添加</el-button>
      </div>
    </div>
    <div class="info_con">
      <div class="info_right">
        <div class="table_con" ref="table_con">
          <vxe-table
            border
            stripe
            class="mytable-scrollbar"
            highlight-hover-row
            size="medium"
            height="100%"
            :data="tableData"
            align="center"
            v-if="!load">
            <vxe-table-column type="seq" title="序号" width="60"></vxe-table-column>
            <vxe-table-column field="orgName" title="部门" width="200"></vxe-table-column>
            <vxe-table-column field="userName" title="人员" width="200"></vxe-table-column>
            <vxe-table-column field="cardNumber" title="银行卡号" min-width="140"></vxe-table-column>
            <vxe-table-column title="操作" width="200">
              <template #default="{ row }">
                <div class="icon_con">
                  <span @click="editRow(row)">编辑</span>
                  <span @click="deleteRow(row)">删除</span>
                </div>
              </template>
            </vxe-table-column>
          </vxe-table>
        </div>
        <div class="table-pagination">
          <pagination
            class="footer sub-margin"
            :page-size.sync="tablePage.pageSize"
            :total="tablePage.totalSize"
            :current-page.sync="tablePage.pageNum"
            layout="slot,prev, pager, next, sizes, jumper"
            @currentChange="onPageChange" />
        </div>
      </div>
    </div>
    <XnDialog
      title="添加银行卡号"
      :visible.sync="addDiaShow"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      top="5vh"
      class="branch_dialog"
      @closed="addDiaShow = false">
      <el-form :model="form" :rules="rules" ref="ruleForm" size="medium" label-width="100px" class="notice_form">
        <template v-if="dialogType === 'add'">
          <el-form-item label="部门：" prop="orgInfo">
            <el-select
              filterable
              v-model="form.orgInfo"
              @change="changeDepart"
              placeholder="请选择部门"
              clearable
              value-key="orgName">
              <el-option v-for="item in orgList" :key="item.orgId" :label="item.orgName" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="姓名：" prop="userInfo">
            <el-select
              filterable
              v-model="form.userInfo"
              :placeholder="form.orgInfo.orgId ? '请选择人员' : '请先选择部门'"
              clearable
              value-key="userName">
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.userName"
                :value="item"
                value-key="userName"></el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="部门：" prop="orgInfo">
            <el-input placeholder="请输入" v-model="form.orgInfo.orgName" disabled></el-input>
          </el-form-item>
          <el-form-item label="姓名：" prop="userInfo">
            <el-input placeholder="请输入" v-model="form.userInfo.userName" disabled></el-input>
          </el-form-item>
        </template>
        <el-form-item label="银行卡号：" prop="cardNum">
          <el-input placeholder="请输入银行卡号" v-model="form.cardNum" maxlength="19" show-word-limit></el-input>
        </el-form-item>
        <div class="btn_save">
          <el-button size="small" @click="cancleAdd">取消</el-button>
          <el-button size="small" class="btnBg" type="primary" @click="submitAdd">确定</el-button>
        </div>
      </el-form>
    </XnDialog>
    <XnDialog
      title="导入银行卡号"
      :visible.sync="importDiaShow"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      top="5vh"
      class="branch_dialog"
      width="1000px">
      <div class="content" @closed="importDiaShow = false">
        <div>
          <span class="import-title">下载模板</span>
          <span class="import-tips">（请先下载人员名单模板，按照模板进行填写）</span>
        </div>
        <el-button class="btn" size="small" type="primary" @click="exportData">银行卡号模板下载</el-button>
        <div>
          <span class="import-title">上传人员名单</span>
          <span class="import-tips">（注意请不要对模板字段进行调整）</span>
        </div>
        <el-upload
          :ref="`Uploader-${uploadId}`"
          class="avatar-uploader"
          :name="uploadId"
          action="#"
          :show-file-list="false"
          :auto-upload="false"
          :http-request="uploadImage"
          :on-change="handleChange"
          accept=".xls,.xlsx">
          <el-button class="btn" size="small" type="primary">上传银行卡号名单</el-button>
        </el-upload>
        <div class="tips" v-if="dialogTable.validCount">
          上传成功，共计导入{{ dialogTable.uploadCount }}条，其中有效条目{{
            dialogTable.validCount
          }}条，确认数据录入请点击确定
        </div>
        <vxe-table
          border
          stripe
          class="mytable-scrollbars"
          highlight-hover-row
          show-overflow
          size="medium"
          :data="dialogTable.cardListList"
          align="center">
          <vxe-table-column type="seq" width="70" title="序号"></vxe-table-column>
          <vxe-table-column field="orgName" title="部门" width="240"></vxe-table-column>
          <vxe-table-column field="userName" title="人员" width="200"></vxe-table-column>
          <vxe-table-column field="cardNumber" title="银行卡号" min-width="140"></vxe-table-column>
        </vxe-table>
      </div>
      <div class="btn_save">
        <el-button size="small" @click="importDiaShow = false">取消</el-button>
        <el-button size="small" class="btnBg" type="primary" @click="importData">确定</el-button>
      </div>
    </XnDialog>
  </div>
</template>

<script>
import {
  getlistCardInfoManage,
  getOrgListBank,
  getUserListByOrgId,
  addCardInfo,
  deleteCardInfo,
  exportCardTemplate,
  uploadCardInfo,
  importCardInfo,
} from '@apis/api-dailyManage.js'
import pagination from '@com/pagination.vue'
import XnDialog from '@com/xnDialog.vue'
export default {
  name: 'dutyBankCard',
  components: { pagination, XnDialog },
  props: {},
  data() {
    const checkCard = (rule, value, cb) => {
      const pattern = /^([1-9]{1})(\d{11}|\d{15}|\d{16}|\d{18})$/
      if (pattern.test(value)) {
        return cb()
      }
      cb(new Error('您输入的银行卡号不是有效格式'))
    }
    const checkName = (rule, value, cb) => {
      if (value.userId || value.orgId) {
        return cb()
      }
      const str = value.userId === '' ? '姓名不能为空' : '部门不能为空'
      cb(new Error(str))
    }
    return {
      load: false,
      tableData: [],
      userInfo: JSON.parse(localStorage.PSKH_USERINFO),
      tablePage: {
        pageNum: 1,
        pageSize: 10,
        totalSize: 0,
      },
      name: '',
      addDiaShow: false,
      importDiaShow: false,
      form: {
        cardNum: '',
        userInfo: {
          userId: '',
          userName: '',
        },
        orgInfo: {
          orgId: '',
          orgName: '',
        },
        id: '',
      },
      rules: {
        userInfo: [
          {
            required: true,
            validator: checkName,
            trigger: 'blur',
          },
        ],
        orgInfo: [
          {
            required: true,
            validator: checkName,
            trigger: 'blur',
          },
        ],
        cardNum: [
          {
            required: true,
            message: '银行卡号不能为空',
            trigger: 'blur',
          },
          {
            validator: checkCard,
            trigger: 'blur',
          },
        ],
      },
      orgList: [],
      userList: [],
      uploadId: Math.random().toString(36).substr(2).toLocaleUpperCase(),
      fileDatalist: [],
      fileTotal: 0,
      fmData: new FormData(),
      fmAppendLength: 0,
      dialogType: '',
      dialogTable: {},
    }
  },
  computed: {},
  filters: {},
  watch: {},
  created() {},
  mounted() {
    this.getData()
  },
  methods: {
    getData() {
      getlistCardInfoManage({
        current: this.tablePage.pageNum,
        size: this.tablePage.pageSize,
        tenantId: localStorage.pskh_tenantId,
        userName: this.name,
      }).then(res => {
        this.load = false
        this.tableData = res.data.records
        this.tablePage.totalSize = res.data.total
      })
    },
    onPageChange(e) {
      this.tablePage.pageNum = e
      this.getData()
    },
    exportData() {
      const req = ''
      const link = document.createElement('a')
      link.target = 'targetName'
      link.href = exportCardTemplate(req)
      link.click()
      link.remove()
    },
    selectFun() {
      this.getData()
    },
    editRow(row) {
      this.dialogType = 'edit'
      this.form = {
        cardNum: row.cardNumber,
        userInfo: {
          userId: row.userId,
          userName: row.userName,
        },
        orgInfo: {
          orgId: row.orgId,
          orgName: row.orgName,
        },
        id: row.id,
      }
      this.addDiaShow = true
    },
    deleteRow(row) {
      this.$confirm('确定要删除该人员银行卡号？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteCardInfo({
            id: row.id,
          }).then(res => {
            if (res.code === 0) {
              this.$message.success('删除成功')
              this.getData()
            }
          })
        })
        .catch(() => {})
    },
    addBankCard() {
      this.dialogType = 'add'
      this.getDepart()
      this.addDiaShow = true
    },
    importBankCard() {
      this.dialogTable = {}
      this.importDiaShow = true
    },
    // 获取所有科室
    getDepart() {
      getOrgListBank({ type: '1' }).then(res => {
        if (res.code === 0) {
          this.orgList = res.data
        }
      })
    },
    getUserListByOrgId() {
      // 获取所有科室
      getUserListByOrgId({
        orgId: this.form.orgInfo.orgId,
      }).then(res => {
        if (res.code === 0) {
          this.userList = res.data
        }
      })
    },
    changeDepart() {
      this.form.userInfo = {
        userId: '',
        userName: '',
      }
      if (this.form.orgInfo.orgId) {
        this.getUserListByOrgId()
      } else {
        this.userList = []
      }
    },
    cancleAdd() {
      this.$refs.ruleForm.resetFields()
      this.addDiaShow = false
      this.form = {
        cardNum: '',
        userInfo: {
          userId: '',
          userName: '',
        },
        orgInfo: {
          orgId: '',
          orgName: '',
        },
        id: '',
      }
    },
    submitAdd() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          addCardInfo({
            cardNumber: this.form.cardNum,
            id: this.form.id,
            orgId: this.form.orgInfo.orgId,
            orgName: this.form.orgInfo.orgName,
            userId: this.form.userInfo.userId,
            userName: this.form.userInfo.userName,
          }).then(res => {
            if (res.code === 0) {
              this.cancleAdd()
              this.$message.success('操作成功')
              this.getData()
            }
          })
        }
      })
    },
    async uploadImage(file) {
      this.fmData.append('file', file.file)
      this.fmAppendLength++
      if (this.fmAppendLength === this.fileTotal) {
        try {
          await uploadCardInfo(this.fmData).then(res => {
            this.loadFile = false
            this.dialogTable = res.data
            if (res.data.validCount === 0) {
              this.$message({
                message: '未识别到有效数据，请查看调整后重新上传。',
                type: 'warning',
              })
            }
          })
        } catch (error) {
        } finally {
          this.loadFile = false
          this.fileDatalist = []
          this.fmData = new FormData()
          this.fmAppendLength = 0
        }
      }
    },
    handleChange(file, fileList) {
      const fileName = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
      if (['xls', 'xlsx'].indexOf(fileName) === -1) {
        this.$message.warning('请上传允许的文件类型')
        return
      }
      file.status === 'ready' && this.fileDatalist.push(file.raw)
      this.fileTotal = document.getElementsByName(this.uploadId)[0].files.length
      if (this.fileDatalist.length === this.fileTotal) {
        this.$refs[`Uploader-${this.uploadId}`].submit()
      }
    },
    importData() {
      if (!this.dialogTable.validCount) {
        this.importDiaShow = false
        return
      }
      importCardInfo(this.dialogTable.cardListList).then(res => {
        if (res.code === 0) {
          this.$message.success('导入成功')
          this.importDiaShow = false
          this.pageNum = 1
          this.getData()
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.duty {
  height: 100%;
  .screen_box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    height: 52px;
    border-bottom: 1px solid #efefef;
    // box-shadow: 0 3px 5px 0 rgba(2, 2, 2, 0.1);
    .select_box {
      display: flex;
      align-items: center;
      .select_li {
        display: flex;
        align-items: center;
        margin-right: 20px;
        .el-select {
          width: 150px;
        }
      }
    }
  }
  .info_con {
    display: flex;
    height: calc(100% - 70px);
    .info_left {
      width: 200px;
    }
    .info_right {
      flex: 1;
      height: 100%;
    }
  }
  .info_detail_title {
    height: 50px;
    line-height: 50px;
    font-weight: bold;
    font-size: 20px;
    padding-left: 20px;
    text-align: center;
    margin-top: 15px;
  }
  .table_con {
    margin: 10px 0 5px;
    height: calc(100% - 50px);
    .icon_con {
      span {
        margin: 0 15px;
        cursor: pointer;
        color: #4a79ba;
      }
      span:last-child {
        color: #f56c6c;
      }
    }
  }
}
.branch_dialog {
  /deep/.el-dialog__body {
    padding-left: 20px;
    padding-right: 20px;
    min-height: auto;
    .el-radio {
      margin-right: 20px;
    }
    .el-textarea {
      margin: 20px 0;
    }
    .btn_save {
      text-align: right;
      margin-top: 20px;
    }
  }
}
.notice_form {
  margin: 0 auto;
  padding: 0 20px;
  width: 100%;
  height: calc(100% - 110px);
  overflow-y: auto;
  padding-bottom: 20px;
  /deep/.el-form-item__label {
    font-weight: 600;
    color: #333;
  }
  /deep/.el-input {
    input {
      border-radius: 4px;
    }
  }
  /deep/.el-form-item {
    margin-bottom: 20px;
  }
  .el-select {
    width: 100%;
  }
  .btn_save {
    display: flex;
    justify-content: center;
  }
}
.content {
  .import-title {
    font-size: 18px;
    color: #333333;
    font-weight: bold;
    text-align: right;
    display: inline-block;
  }
  .import-tips {
    color: #909399;
    margin-right: 30px;
  }
  .btn {
    margin: 20px 0;
  }
  .tips {
    margin-bottom: 20px;
  }
}
.mytable-scrollbars {
  /deep/.vxe-table--body-wrapper {
    max-height: 300px;
  }
}
</style>
